﻿using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Media3D;
using Uipath_License.Model;
using static System.Net.Mime.MediaTypeNames;

namespace Uipath_License.Tools
{
    public class Uipath_LicenseHelper
    {

        string UipathEexName = "UiPath.LicenseTool.exe";

        public string GetUipath_Path() 
        {
            string res = "0";
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\UiPath"))
            {
                foreach (string subkey_name in key.GetSubKeyNames())
                {
                    RegistryKey teamsKey = key.OpenSubKey(subkey_name);
                     res = teamsKey.GetValue("InstallDir").ToString();
                    if (!string.IsNullOrEmpty(res))
                    {
                        return res;
                    }
                }
            }
            return res;
        }

        /// <summary>
        /// 获得字符串中开始和结束字符串中间得值
        /// </summary>
        /// <param name="str">要截取的字符串</param>
        /// <param name="sta">开始字符</param>
        /// <param name="end">结束字符</param>
        /// <returns></returns> 
        public string GetMiddleValue(string text,string left, string right)
        {
            //判断是否为null或者是empty
            if (string.IsNullOrEmpty(left))
                return "";
            if (string.IsNullOrEmpty(right))
                return "";
            if (string.IsNullOrEmpty(text))
                return "";
            //判断是否为null或者是empty

            int Lindex = text.IndexOf(left); //搜索left的位置

            if (Lindex == -1)
            { //判断是否找到left
                return "";
            }

            Lindex = Lindex + left.Length; //取出left右边文本起始位置

            int Rindex = text.IndexOf(right, Lindex);//从left的右边开始寻找right

            if (Rindex == -1)
            {//判断是否找到right
                return "";
            }

            return text.Substring(Lindex, Rindex - Lindex);//返回查找到的文本
        }

        /// <summary>
        /// 获取License信息
        /// </summary>
        public string GetLicense_Message() 
        {
            string uipath_Path= GetUipath_Path()+ UipathEexName;
            string res = CommandHelper.RunCommand(uipath_Path,10, "info");
            if (res.Contains("LicenseExpired"))
            {
                res = "License过期或没有安装";
                return res;
            }
            if (res.Contains("NoLicenseAvailable"))
            {
                res = "未激活";
                return res;
            }
            if (res.Contains("ActiveLicense"))
            {
                res = $"License有效\n\n" +
                    $"激活 ID: {GetMiddleValue(res, "婵€娲?ID: ", "璁稿彲璇佷唬鐮? ")}\n" +
                    $"License: {GetMiddleValue(res, "璁稿彲璇佷唬鐮? ", "寮€濮嬫棩鏈?(UTC): ")}\n" +
                    $"开始日期(UTC): {GetMiddleValue(res, "寮€濮嬫棩鏈?(UTC): ", "缁撴潫鏃ユ湡 (UTC): ")}\n" +
                    $"结束日期(UTC): {GetMiddleValue(res, "缁撴潫鏃ユ湡 (UTC): ", "瀹介檺鏈?(澶?")}\n" +
                    $"宽限期(天): {GetMiddleValue(res, "瀹介檺鏈?(澶?: ", "鍖呮嫭瀹介檺鏈熷湪鍐呯殑缁撴潫鏃ユ湡 (UTC): ")} \n" +
                    $"包括宽限期的结束日期(UTC): {GetMiddleValue(res, "鍖呮嫭瀹介檺鏈熷湪鍐呯殑缁撴潫鏃ユ湡 (UTC): ", "涓嬫妫€鏌ユ棩鏈? ")}\n" +
                    $"下次检查日期: {GetMiddleValue(res, "涓嬫妫€鏌ユ棩鏈? ", " Success")}";
            }
            return res;
        }

        /// <summary>
        /// 在线激活
        /// </summary>
        /// <returns></returns>
        public string Net_Activate(string licenseCode) 
        {
            string res=string.Empty;
            string uipath_Path = GetUipath_Path() + UipathEexName;
            res = CommandHelper.RunCommand(uipath_Path, 10, new string[]{ "activate", "-l", licenseCode });
            return res;
        }


        /// <summary>
        /// 在线获取License
        /// </summary>
        public Response_License NetGetLicense() 
        {
            //在线获取License
            string url = "https://licensing01api.azurewebsites.net/api/Customer/RegisterCustomerAsync";
            //string url = "http://localhost:5668/Home/GetLicense";
            Request_License request_License = new Request_License();
            request_License.Request_License_Default();
            string response_str;
            try
            {
                response_str = HttpHelper.PostUrlString(url, JsonConvert.SerializeObject(request_License));
            }
            catch (Exception ex)
            {
                response_str = ex.Message;
            }
            Response_License response_License = JsonConvert.DeserializeObject<Response_License>(response_str);
            return response_License;
           
        }

        /// <summary>
        /// 释放License/停用License
        /// </summary>
        /// <returns></returns>
        public string Net_Deactivate() 
        {
            string res = "0";
            string uipath_Path = GetUipath_Path() + UipathEexName;
            res = CommandHelper.RunCommand(uipath_Path, 10, "deactivate");
            return res;
        }

        /// <summary>
        /// 在线更新License
        /// </summary>
        /// <returns></returns>
        public string Net_Update() 
        {
            string res = "0";
            string uipath_Path = GetUipath_Path() + UipathEexName;
            res = CommandHelper.RunCommand(uipath_Path, 10, "update");
            return res;
        }


        /// <summary>
        /// 离线停用License
        /// </summary>
        /// <returns></returns>
        public string DisableLicense() 
        {
            string res = "0";
            string uipath_Path = GetUipath_Path() + UipathEexName;
            res = CommandHelper.RunCommand(uipath_Path, 10, "deactivation-request");
            if (res.Contains("No license exist for"))
            {
                res = "不存在License";
            }
            if(res.Contains("鍋滅敤浠ょ墝: "))
            {
                res = GetMiddleValue(res, "鍋滅敤浠ょ墝: ", "宸叉垚鍔熷湪鏈");
            }
            return res;
        }

        /// <summary>
        /// 离线许可证生成
        /// </summary>
        /// <returns></returns>
        public string OfflineLicenseGenerated(string license) 
        {
            string res = "0";
            string uipath_Path = GetUipath_Path() + UipathEexName;
            res = CommandHelper.RunCommand(uipath_Path, 10, "activation-request -l " + license);
            res = GetMiddleValue(res, "婵€娲讳护鐗? ", "杞埌 ");
            return res;
        }


        /// <summary>
        /// 离线激活
        /// </summary>
        /// <param name="license"></param>
        /// <returns></returns>
        public string OfflineActivation(string license) 
        {
            string txtPath = System.AppDomain.CurrentDomain.BaseDirectory + "license.txt";
            if (!File.Exists(txtPath))
            {
                FileStream fs1 = new FileStream(txtPath, FileMode.Create, FileAccess.Write);//创建写入文件 
                StreamWriter sw = new StreamWriter(fs1);
                sw.WriteLine(license);//开始写入值
                sw.Close();
                fs1.Close();
            }
            else
            {
                FileStream fs = new FileStream(txtPath, FileMode.Open, FileAccess.Write);
                StreamWriter sr = new StreamWriter(fs);
                sr.WriteLine(license);//开始写入值
                sr.Close();
                fs.Close();
            }
            string res = "0";
            string uipath_Path = GetUipath_Path() + UipathEexName;
            res = CommandHelper.RunCommand(uipath_Path, 10, "activate-offline -f " + txtPath);
            File.Delete(txtPath);
            //res = GetMiddleValue(res, "婵€娲讳护鐗? ", "杞埌 ");
            if (res.Contains("Incompatible license"))
            {
                return "请检查许可证格式";
            }
            
            return res;
        }
    }
}
